package org.example.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class LoginServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    // 模拟用户数据库，存储用户名 -> 密码 + 个人信息
    private static Map<String, User> users = new HashMap<>();

    static {
        users.put("admin", new User("admin", "123456", "计算机科学", "2023", "1班", "12345678901"));
        users.put("user1", new User("user1", "password", "软件工程", "2022", "2班", "13800138000"));
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 处理登录逻辑
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if (username == null || password == null) {
            response.sendRedirect("error.jsp");
            return;
        }

        User user = users.get(username);
        if (user != null && user.getPassword().equals(password)) {
            // 登录成功，保存用户信息到 session
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            // 跳转信息显示页面
            request.getRequestDispatcher("info.jsp").forward(request, response);
        } else {
            // 登录失败，跳转错误页面
            response.sendRedirect("error.jsp");
        }
    }

    // 响应登录页面取消按钮，重定向到登录页
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String action = request.getParameter("action");
        if ("cancel".equals(action)) {
            response.sendRedirect("login.jsp");
        } else {
            response.sendRedirect("login.jsp");
        }
    }

    // 定义内部静态类保存用户信息
    public static class User {
        private String username;
        private String password;
        private String major;
        private String grade;
        private String clazz;
        private String contact;

        public User(String username, String password, String major, String grade, String clazz, String contact) {
            this.username = username;
            this.password = password;
            this.major = major;
            this.grade = grade;
            this.clazz = clazz;
            this.contact = contact;
        }

        // Getter
        public String getUsername() { return username; }
        public String getPassword() { return password; }
        public String getMajor() { return major; }
        public String getGrade() { return grade; }
        public String getClazz() { return clazz; }
        public String getContact() { return contact; }
    }
}
